package com.cictec.middleware.gps.service;

import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cictec.middleware.commons.cache.ecache.EHCacheUtils;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.core.entity.BusCharter;
import com.cictec.middleware.gps.service.feign.MiddlewareDcFeignClient;

/**
 * 包车服务
 * @author ql
 *
 */
@Service
public class BusCharterService {

	private static Logger logger = LoggerFactory.getLogger(BusCharterService.class);
	
	private static String BUS_CHARTER_PLAN = "bus-charter-plan"; // 包车计划
	
	@Autowired
	private MiddlewareDcFeignClient middlewareDcFeignClient;
	
	
	/**
	 * 【缓存】【按天分组】加载指定日期包车计划
	 * @param date
	 */
	public void loadBusCharterPlan(Date date){
		logger.debug("【BusCharterService】 加载 {} 包车计划到缓存", DateUtils.formatDate(new Date()));
		
		String cacheKey =  DateUtils.formatDate(date).replaceAll("-", ""); 
		List<BusCharter> lineDeviatePlanList = selectBusCharterByParams("", date);
		EHCacheUtils.setValue(BUS_CHARTER_PLAN, cacheKey, lineDeviatePlanList);
		
//		lineDeviatePlanList = EHCacheUtils.getValue(BUS_CHARTER_PLAN, cacheKey);
	}
	
	/**
	 * 【缓存】清空缓存中包车计划
	 */
	public void clearBusCharterPlan(){
		logger.info("【BusCharterService】 清空包车计划缓存");
		try {
			EHCacheUtils.removeEhcache(BUS_CHARTER_PLAN);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 【数据库】数据库加载包车
	 * @param busUuid
	 * @param date
	 * @return
	 */

	public List<BusCharter> selectBusCharterByParams(String busUuid, Date date){

		return middlewareDcFeignClient.getBusCharter(busUuid, date);
	}
	
	
	/**
	 * 根据时间和当前站的序号判断是否在包车计划区域。
	 * @param busUuid		 线路uuid 【必填】
	 * @param lineType 		  线路类型 【必填】
	 * @param time			 位置点上传时间
	 * @param stationSequence 站点序号
	 * @return false:未在包车计划内，true：在包车计划内
	 */
	public boolean isInBusCharterPlan(String busUuid, Date time) {
		if(PMSUtils.isEmpty(busUuid)){
			return false;
		}
		
		String cacheKey =  DateUtils.formatDate(time).replaceAll("-", ""); 
		List<BusCharter> lineBusCharterPlanList = EHCacheUtils.getValue(BUS_CHARTER_PLAN, cacheKey);
		
		if(lineBusCharterPlanList == null){
			loadBusCharterPlan(time);
			lineBusCharterPlanList = EHCacheUtils.getValue(BUS_CHARTER_PLAN, cacheKey);
		}		
		
		for (BusCharter charter : lineBusCharterPlanList) {
			
			if(charter.getCtBusUuid() != null && charter.getCtBusUuid().equals(busUuid)
					&& charter.getStartTime().getTime()  < time.getTime() && charter.getEndTime().getTime() >= time.getTime()
					){
				return true;
			}
		}

		return false;
	}
}
